﻿define(["moment"], function (moment) {
    return ["$state", "$scope", "$rootScope", "$filter", "$stateParams", "config", "MMWService", "$mdDialog", "$timeout", "$calculater",
        function ($state, $scope, $rootScope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $calculater) {
            $scope.init = function () {
                let today = new Date();
                $scope.conditions = {
                    pack_date_start: getPrevDay(today, 6),
                    pack_date_end: getPrevDay(today, -1),
                    pack_user: '',
                    area_no: '',
                    op_no: '',
                    product_no: '',
                    box_no: '',
                    input_no:''     //M#94816 添加投入QR CODE 查詢 能夠排查包裝內容(input_no = 成品、生產批、包裝 序號)
                };
                $scope.selectAll = false;
                $scope.datalist = [];   // 列表
                $scope.filterItem = {};
                $scope.PageConfig = {
                    page: 0,
                    page_count: 25
                };
            };

            // 获取N天前日期
            function getPrevDay(date, days) {
                return new Date(date - days * 24 * 60 * 60 * 1000);
            }
            function FormatDate(date) {
                let seperator1 = "/";
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                let currentdate = year + seperator1 + month + seperator1 + strDate;
                return currentdate;
            }

            // 人員開窗
            $scope.loadUserNo = function () {
                $scope.$root.showQueryList({
                    key: 'userno',
                    header: [
                        { label: $filter('translate')('common.queryList.employee_c'), code: 'userno' }, // 人員編號
                        { label: $filter('translate')('common.queryList.employee_n'), code: 'username' } // 人員名稱
                    ],
                    query: function (conditions, feedback) {
                        $MMWService.pageNumberInfoGet({
                            page_mode: 'package_print_acc_info'
                        }, function (response) {
                            feedback(response);
                        });
                    },
                    selectCode: $scope.conditions.pack_user,
                    confirm: function (selectItem, dialog) {
                        $scope.conditions.pack_user = selectItem.userno; // 人員編號
                        dialog.hide();
                    }
                });
            };

            // 包裝明細
            $scope.showDetail = function (item) {
                var dataList = [];
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_CRAFT.package_box_no_detail_info_get',
                    content: { box_no: item.box_no, box_level: item.box_level },
                    success: function (data) {                       
                        if (data.dataList && data.dataList.length > 0) {
                            dataList = data.dataList;
                            $scope.isSelectAll = false;
                            $mdDialog.dialog(
                                'module/moduleB/program/B14/showDetail.html',
                                function (dialog) {
                                    return {
                                        css_url: 'module/moduleB/program/B14/showDetail.css',
                                        item: item,
                                        itemList: dataList,
                                        back: function () {
                                            dialog.hide();
                                        },
                                        close: function () {
                                            dialog.hide();
                                        },
                                        PageConfig: {
                                            page: 0,
                                            page_count: 25
                                        },
                                        filterItem: [],
                                        getPages: function(list, PageConfig, filterItem) {
                                            if (list) {
                                                var temp_list = list.filter(function (item, index, array) {
                                                    var isOK = true,
                                                        keys = Object.keys(filterItem);
                                                    for (var i = 0; i < keys.length; i++) {
                                                        var key = keys[i];
                                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                            if (item[key].indexOf(filterItem[key]) == -1) {
                                                                isOK = false;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    return isOK;
                                                });
                                                if (PageConfig) {
                                                    PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count) || 1;
                                                    if (PageConfig.page >= PageConfig.total_page) {
                                                        PageConfig.page = 0;
                                                    }
                                                    var index = PageConfig.page * PageConfig.page_count;
                                                    return temp_list.slice(index, index + PageConfig.page_count);
                                                } else {
                                                    return temp_list;
                                                }
                                            } else {
                                                return list;
                                            }
                                        }
                                    };
                                }
                            );
                        } else {
                            $scope.isSelectAll = false;
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        };
                    }
                });
            }

            // 生產線開窗
            $scope.loadAreaNo = function () {
                $scope.$root.showQueryList({
                    key: 'areano',
                    header: [
                        { label: $filter('translate')('common.queryList.area_c'), code: 'areano' }, // 生產線編號
                        { label: $filter('translate')('common.queryList.area_n'), code: 'areaname' } // 生產線名稱
                    ],
                    query: function (conditions, feedback) {
                        $MMWService.pageNumberInfoGet({
                            page_mode: 'package_print_area_no_info',
                            query_condition_info: []
                        }, function (response) {
                            feedback(response);
                        });
                    },
                    selectCode: $scope.conditions.area_no,
                    confirm: function (selectItem, dialog) {
                        $scope.conditions.area_no = selectItem.areano; // 生產線編號
                        dialog.hide();
                    }
                });
            };

            // 作業站開窗
            $scope.loadOpNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'package_print_op_no_info',
                    header: [
                        { label: $filter('translate')('common.queryList.op_c'), code: 'opno' }, // 作業站編號
                        { label: $filter('translate')('common.queryList.op_n'), code: 'opname' } // 作業站名稱
                    ],
                    selectCode: $scope.conditions.op_no,
                    confirm: function (selectItem) {
                        $scope.conditions.op_no = selectItem.opno; // 作業站編號
                    }
                });
            };

            // 产品開窗
            $scope.loadProductNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'package_print_product_no_info',
                    header: [
                        { label: $filter('translate')('common.queryList.item_c'), code: 'productno' }, 
                        { label: $filter('translate')('B1402.list.product_version'), code: 'productversion' },
                        { label: $filter('translate')('common.queryList.item_n'), code: 'productname' },
                        { label: $filter('translate')('common.queryList.item_spec'), code: 'itemspec' }, 
                    ],
                    selectCode: $scope.conditions.product_no,
                    confirm: function (selectItem) {
                        $scope.conditions.product_no = selectItem.productno; // 作業站編號
                    }
                });
            };

            // 包装序号扫码
            $scope.qrcode_box_no = function () {
                $rootScope.OpenScanner({
                    after: function (result) {
                        $scope.conditions.box_no = result.text;
                    },
                    exception: function () {
                        //目前裝置無法使用相機
                        $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation: 'landscape'
                });
            };
            //M#94816 添加投入QR CODE 查詢 能夠排查包裝內容(input_no = 成品、生產批、包裝 序號)
            $scope.qrcode_input_no = function () {
                $rootScope.OpenScanner({
                    after: function (result) {
                        $scope.conditions.input_no  = result.text;
                    },
                    exception: function () {
                        //目前裝置無法使用相機
                        $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation: 'landscape'
                });
            };
            $scope.getPages = function (list, PageConfig, filterItem, orderItem) {
                if (list) {
                    var temp_list = list.filter(function (item, index, array) {
                        var isOK = true,
                            keys = Object.keys(filterItem);
                        for (var i = 0; i < keys.length; i++) {
                            var key = keys[i];
                            if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                if (item[key].indexOf(filterItem[key]) == -1) {
                                    isOK = false;
                                    break;
                                }
                            }
                        }
                        return isOK;
                    });
                    if (PageConfig) {
                        PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count) || 1;
                        if (PageConfig.page >= PageConfig.total_page) {
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page * PageConfig.page_count;
                        return temp_list.slice(index, index + PageConfig.page_count);
                    } else {
                        return temp_list;
                    }
                } else {
                    return list;
                }
            };

            // 查询
            $rootScope.search = function () {
                // 检查日期相差范围是否大于3个月
                if (getD($scope.conditions.pack_date_start, $scope.conditions.pack_date_end)) {
                    $scope.$root.showAlert($filter('translate')('B1402.showAlert.column1'));
                    return;
                }
                var content = {
                    pack_date_start: $scope.conditions.pack_date_start ? FormatDate($scope.conditions.pack_date_start) : '',
                    pack_date_end: $scope.conditions.pack_date_end ? FormatDate($scope.conditions.pack_date_end) : '',
                    pack_user: $scope.conditions.pack_user,
                    area_no: $scope.conditions.area_no,
                    op_no: $scope.conditions.op_no,
                    product_no: $scope.conditions.product_no,
                    box_no: $scope.conditions.box_no,
                    input_no:$scope.conditions.input_no
                };

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_CRAFT.package_print_info_get',
                    content: content,
                    success: function (data) {
                        if (data.dataList.length == 0) {
                            $scope.$root.showAlert($filter('translate')('B1402.showAlert.column2'));
                            $scope.datalist = [];
                        } else {
                            $scope.datalist = data.dataList;
                        }
                    },
                    error: function (data) {
                        $rootScope.showAlert(data.Message);
                    }
                });
            };

            // 检查日期是否大于3个月
            function getD(sDate, endDate) {
                var sDate = new Date(sDate);
                var eDate = new Date(endDate);
                if (eDate.getFullYear() - sDate.getFullYear() > 1) {//先比较年
                    return true;
                } else if (eDate.getMonth() - sDate.getMonth() > 3) {//再比较月
                    return true;
                } else if (eDate.getMonth() - sDate.getMonth() == 3) {
                    if (eDate.getDate() - sDate.getDate() >= 1) {
                        return true;
                    }
                } else if (eDate.getFullYear() - sDate.getFullYear() == 1) {
                    if (eDate.getMonth() + 12 - sDate.getMonth() > 3) {
                        return true;
                    } else if (eDate.getMonth() + 12 - sDate.getMonth() == 3) {
                        if (eDate.getDate() - sDate.getDate() >= 1) {
                            return true;
                        }
                    }
                }
                return false;
            }

            // 全选
            $scope.selectAllBoxes = function () {
                $scope.selectAll = !$scope.selectAll;
                $scope.datalist.forEach(function (item) {
                    item.isSelect = $scope.selectAll;
                });
                if ($scope.datalist.length == 0) {
                    $scope.selectAll = false;
                }
            };

            // 选择一行
            $scope.selectBox = function (event, item) {
                event.stopPropagation();
                item.isSelect = !item.isSelect

                var checkarr = []
                $scope.datalist.forEach(function (data) {
                    if (data.isSelect) {
                        checkarr.push(data)
                    }
                })
                if (checkarr.length === $scope.datalist.length) {
                    $scope.selectAll = true;
                } else {
                    $scope.selectAll = false;
                }
            };

            // 补印
            $scope.print = function () {
                let selectedList = $scope.datalist.filter(item => item.isSelect);
                if (selectedList.length == 0) {
                    $rootScope.showAlert($filter('translate')('B1402.showAlert.column3'));
                    return;
                }
                let printList = selectedList.map(s => {
                    return {
                        box_no: s.box_no,
                        box_level: s.box_level
                    }
                });
                var content = {
                    printList: printList
                }
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_CRAFT.package_box_no_print_batch_process',
                    content: content,
                    success: function (data) {
                        if (data.printUrlList.length > 0) {
                            var command_lines = [];
                            var run_card_pdf_urls = [];
                            data.printUrlList.forEach(p => {
                                // 執行標籤列印 
                                if (p.command_lines){
                                    command_lines.push(p.command_lines);
                                }
                                if (p.run_card_pdf_url) {
                                    run_card_pdf_urls.push(p.run_card_pdf_url);
                                }
                            });
                            
                            if (command_lines.length > 0) {
                                printTag(command_lines, 0);
                            }

                            // 執行 PDF列印
                            if (run_card_pdf_urls.length > 0) {
                                printBatch(run_card_pdf_urls, 0);
                            }

                            $scope.search();
                        } else {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    }
                });
            };

            // 批量打印
            function printBatch(run_card_pdf_urls, index) {
                if (index < run_card_pdf_urls.length) {
                    pdf_url = run_card_pdf_urls[index];
                    if (pdf_url.indexOf('http://') == -1) {
                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                    }
                    print(pdf_url, function callback() {
                        index = index + 1;
                        printBatch(run_card_pdf_urls, index);
                    });

                }
            };

            // PDF列印
            function print(pdf_url, callback) {
                // 20201110 modify by WeiTing for M#80602 - 增加多張列印功能(printCount)。
                if (window.nodeRequire) {
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if (sumatraPDF) {
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try {
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        } catch (e) {
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if (!fs.existsSync(RuncardPath)) {
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })
    
                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $rootScope.showLoading();
                            // 20201110 modify by WeiTing for M#80602 - 不跳列印介面，直接使用預設列印機進行列印(printToDefault)。
                            var _fn = sumatraPDF.printToDefault;
                            _fn({
                                path: dist_path,
                                success: function () {
                                    callback();
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                },
                                error: function (error) {
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            };

            // 標籤列印
            function printTag(commandLines, index) {
                if (commandLines && index < commandLines.length) {
                    if (window.nodeRequire) {
                        var exec = window.nodeRequire('child_process').exec;
                        exec(commandLines[index], function (error, stdout, stderr) {
                            if (error) {
                                $rootScope.showAlert($filter('translate')('B1201.msg.cantprint'));
                            }
                            index = index + 1;
                            printTag(commandLines, index);
                        });
                    }
                }
            };

        }
    ];
});
